import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-07-14
 * Time: 19:35
 */
public class test3 {

    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};

    public int rotApple (ArrayList<ArrayList<Integer>> grid){
        int m = grid.size();
        int n = grid.get(0).size();
        boolean[][] vis = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(grid.get(i).get(j)==2){
                    queue.add(new int[]{i,j});
                }
            }
        }

        int ret = 0;
        while (!queue.isEmpty()){
            int sz = queue.size();
            while (sz-- != 0){
                int[] t = queue.poll();
                int a = t[0];
                int b = t[1];
                for(int i=0;i<4;i++){
                    int x = a + dx[i];
                    int y = b + dy[i];
                    if(x>=0 && x<m && y>=0 && y<n && !vis[x][y] && grid.get(x).get(y)==1){
                        vis[x][y] = true;
                        queue.add(new int[]{x,y});
                    }
                }
            }
            ret++;
        }
        // 判断剩余的苹果
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(grid.get(i).get(j)==1 && !vis[i][j]){
                    return -1;
                }
            }
        }
        return ret-1;
    }

}
